package com.weetop.cfw.home_page.activity

import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.coorchice.library.SuperTextView
import com.google.gson.reflect.TypeToken
import com.kongzue.dialog.v3.MessageDialog
import com.weetop.cfw.R
import com.weetop.cfw.base.presenter.imp.SearchPresenterImp
import com.weetop.cfw.base.ui.activity.CommonBaseActivity
import com.weetop.cfw.base.view.SearchView
import com.weetop.cfw.bean.PopularSearchBean
import com.weetop.cfw.utils.MMKVUtils
import com.zhy.view.flowlayout.FlowLayout
import com.zhy.view.flowlayout.TagAdapter
import kotlinx.android.synthetic.main.activity_search.*


/**
 * 搜索界面
 */
class SearchActivity : CommonBaseActivity(), View.OnClickListener, TextView.OnEditorActionListener,
    SearchView {

    companion object {
        private const val SEARCH_TYPE = "search_type"

        fun startSearchActivity(commonBaseActivity: CommonBaseActivity, type: Int) {
            val intent = Intent(commonBaseActivity, SearchActivity::class.java)
            intent.putExtra(SEARCH_TYPE, type)
            ActivityUtils.startActivity(intent)
        }

        fun startSearchActivity(commonBaseActivity: CommonBaseActivity, type: Int,index:Int) {
            val intent = Intent(commonBaseActivity, SearchActivity::class.java)
            intent.putExtra(SEARCH_TYPE, type)
            intent.putExtra("index", index)

            ActivityUtils.startActivity(intent)
        }

    }

    private var searchType = 1//搜索类型 1:厂房搜索 其它:商业云课和管理音频搜索

    /**
     * 商业云课/管理音频搜索记录
     */
    private val cloudClassAudioSearchHistoryList = ArrayList<String>()
    /**
     * 厂房/仓库租售搜索记录
     */
    private val workshopWarehouseSearchHistoryList = ArrayList<String>()

    private lateinit var searchPresenterImp: SearchPresenterImp

    override fun getLayoutId() = R.layout.activity_search

    override fun initView(savedInstanceState: Bundle?) {
        setViewsOnClickListener(this, imageSearchBack, textSearch, imageClearHistorySearch)
        editSearchContent.setOnEditorActionListener(this)
    }

    private var index=0
    override fun initData(savedInstanceState: Bundle?) {

        searchPresenterImp = SearchPresenterImp()
        searchPresenterImp.attachView(this)

        searchType = intent.getIntExtra(SEARCH_TYPE, 1)
        index=intent.getIntExtra("index",0)



        if (searchType == 1) {
            searchPresenterImp.getPopularSearchList(this@SearchActivity, "cf")
        } else if (searchType == 2) {
            searchPresenterImp.getPopularSearchList(this@SearchActivity, "cy")
        }
        KeyboardUtils.showSoftInput()

    }


    override fun onResume() {
        super.onResume()
        initHistorySearchData()

    }

    /**
     * 初始化历史搜索和热门搜索数据
     */
    private fun initHistorySearchData() {
        if (searchType == 1) {
            val workshopWarehouseHistoryJson = MMKVUtils.getWorkshopWarehouseHistorySearch()
            if (workshopWarehouseHistoryJson.isNotEmpty()) {
                workshopWarehouseSearchHistoryList.clear()
                workshopWarehouseSearchHistoryList.addAll(
                    GsonUtils.fromJson(
                        workshopWarehouseHistoryJson,
                        object : TypeToken<ArrayList<String>>() {}.type
                    )
                )
                historySearchTagFlow.adapter =
                    object : TagAdapter<String>(workshopWarehouseSearchHistoryList) {
                        override fun getView(parent: FlowLayout?, position: Int, t: String?): View {
                            val historySearchFlowLayoutView =
                                LayoutInflater.from(this@SearchActivity).inflate(
                                    R.layout.layout_item_history_search_flow,
                                    parent,
                                    false
                                )
                            val textHistorySearchItem =
                                historySearchFlowLayoutView.findViewById<SuperTextView>(R.id.textHistorySearchItem)
                            textHistorySearchItem.text =
                                workshopWarehouseSearchHistoryList[position]
                            return historySearchFlowLayoutView
                        }
                    }
            }
            LogUtils.eTag("workshopWarehouseSearchHistoryList", workshopWarehouseSearchHistoryList)
        } else {
            val cloudClassAudioHistoryJson = MMKVUtils.getCloudClassAudioHistorySearch()
            if (cloudClassAudioHistoryJson.isNotEmpty()) {
                cloudClassAudioSearchHistoryList.clear()
                cloudClassAudioSearchHistoryList.addAll(
                    GsonUtils.fromJson(
                        cloudClassAudioHistoryJson,
                        object : TypeToken<ArrayList<String>>() {}.type
                    )
                )
                historySearchTagFlow.adapter =
                    object : TagAdapter<String>(cloudClassAudioSearchHistoryList) {
                        override fun getView(parent: FlowLayout?, position: Int, t: String?): View {
                            val historySearchFlowLayoutView =
                                LayoutInflater.from(this@SearchActivity).inflate(
                                    R.layout.layout_item_history_search_flow,
                                    parent,
                                    false
                                )
                            val textHistorySearchItem =
                                historySearchFlowLayoutView.findViewById<SuperTextView>(R.id.textHistorySearchItem)
                            textHistorySearchItem.text = cloudClassAudioSearchHistoryList[position]
                            return historySearchFlowLayoutView
                        }
                    }
            }
            LogUtils.eTag("cloudClassAudioSearchHistoryList", cloudClassAudioSearchHistoryList)
        }

        historySearchTagFlow.setOnTagClickListener { view, position, parent ->
            if (searchType == 1) {
                SearchResultActivity.startSearchResultActivity(
                    this,
                    workshopWarehouseSearchHistoryList[position],
                    index
                )
            } else if (searchType == 2) {
                CloudCurriculumAndAudioSearchResultActivity.startCloudCurriculumAndAudioSearchResultActivity(
                    this,
                    cloudClassAudioSearchHistoryList[position]
                )
            }
            true
        }
    }

    override fun onClick(p0: View?) {
        when (p0?.id) {
            R.id.imageSearchBack -> ActivityUtils.finishActivity(this)
            R.id.textSearch -> startSearchResult()
            R.id.imageClearHistorySearch -> {
                MessageDialog.show(this@SearchActivity, "提示", "确定要清除历史搜索记录吗？", "确定", "取消")
                    .setOnOkButtonClickListener { baseDialog, v ->
                        if (searchType == 1) {
                            workshopWarehouseSearchHistoryList.clear()
                            MMKVUtils.clearWorkshopWarehouseHistorySearch()
                            historySearchTagFlow.adapter =
                                object : TagAdapter<String>(workshopWarehouseSearchHistoryList) {
                                    override fun getView(
                                        parent: FlowLayout?,
                                        position: Int,
                                        t: String?
                                    ): View {
                                        val historySearchFlowLayoutView =
                                            LayoutInflater.from(this@SearchActivity).inflate(
                                                R.layout.layout_item_history_search_flow,
                                                parent,
                                                false
                                            )
                                        val textHistorySearchItem =
                                            historySearchFlowLayoutView.findViewById<SuperTextView>(
                                                R.id.textHistorySearchItem
                                            )
                                        textHistorySearchItem.text =
                                            workshopWarehouseSearchHistoryList[position]
                                        return historySearchFlowLayoutView
                                    }
                                }
                        } else {
                            cloudClassAudioSearchHistoryList.clear()
                            MMKVUtils.clearCloudClassAudioHistorySearch()
                            historySearchTagFlow.adapter =
                                object : TagAdapter<String>(cloudClassAudioSearchHistoryList) {
                                    override fun getView(
                                        parent: FlowLayout?,
                                        position: Int,
                                        t: String?
                                    ): View {
                                        val historySearchFlowLayoutView =
                                            LayoutInflater.from(this@SearchActivity).inflate(
                                                R.layout.layout_item_history_search_flow,
                                                parent,
                                                false
                                            )
                                        val textHistorySearchItem =
                                            historySearchFlowLayoutView.findViewById<SuperTextView>(
                                                R.id.textHistorySearchItem
                                            )
                                        textHistorySearchItem.text =
                                            cloudClassAudioSearchHistoryList[position]
                                        return historySearchFlowLayoutView
                                    }
                                }
                        }
                        baseDialog.doDismiss()
                        true
                    }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        searchPresenterImp.detachView()
    }

    /**
     * 跳转到搜索结果界面
     */
    private fun startSearchResult() {
        if (searchType == 1) {
            if (editSearchContent.text.toString().trim().isNotEmpty()) {//如果有输入搜索内容
                if (workshopWarehouseSearchHistoryList.size < 20) {//搜索记录保存20条
                    workshopWarehouseSearchHistoryList.add(editSearchContent.text.toString().trim())
                    MMKVUtils.saveWorkshopWarehouseHistorySearch(workshopWarehouseSearchHistoryList)
                }
            }
            SearchResultActivity.startSearchResultActivity(
                this,
                editSearchContent.text.toString().trim(),
                index
            )
        } else {
            if (editSearchContent.text.toString().trim().isNotEmpty()) {//如果有输入搜索内容
                if (cloudClassAudioSearchHistoryList.size < 20) {//搜索记录保存20条
                    cloudClassAudioSearchHistoryList.add(editSearchContent.text.toString().trim())
                    MMKVUtils.saveCloudClassAudioHistorySearch(cloudClassAudioSearchHistoryList)
                }
            }
            CloudCurriculumAndAudioSearchResultActivity.startCloudCurriculumAndAudioSearchResultActivity(
                this,
                editSearchContent.text.toString().trim()
            )
        }
    }

    override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            startSearchResult()
            return true
        }
        return false
    }

    /**
     * 热门搜索数据获取成功
     */
    override fun getPopularSearchDataSuccess(popularSearchBean: PopularSearchBean?) {
        if (popularSearchBean != null) {
            hotSearchTagFlow.adapter =
                object : TagAdapter<PopularSearchBean.DataBean>(popularSearchBean.data) {
                    override fun getView(
                        parent: FlowLayout?,
                        position: Int,
                        t: PopularSearchBean.DataBean?
                    ): View {
                        val hotSearchFlowLayoutView = LayoutInflater.from(this@SearchActivity)
                            .inflate(R.layout.layout_item_hot_search_flow, parent, false)
                        val textHotSearchItem =
                            hotSearchFlowLayoutView.findViewById<SuperTextView>(R.id.textHotSearchItem)
                        textHotSearchItem.text = t?.key
                        return hotSearchFlowLayoutView
                    }
                }
            hotSearchTagFlow.setOnTagClickListener { _, position, _ ->
                if (searchType == 1) {
                    SearchResultActivity.startSearchResultActivity(
                        this,
                        popularSearchBean.data[position].key,
                        index
                    )
                } else if (searchType == 2) {
                    CloudCurriculumAndAudioSearchResultActivity.startCloudCurriculumAndAudioSearchResultActivity(
                        this,
                        popularSearchBean.data[position].key
                    )
                }
                true
            }
        }
    }
}
